//
//  SideMeunViewController.m
//  MINFOBBS
//
//  Created by juvid on 13-11-11.
//  Copyright (c) 2013年 minfo. All rights reserved.
//

#import "SideMeunViewController.h"
#import "MFSideMenuContainerViewController.h"
#import "ChangCity.h"
//#import "ChangCityViewController.h"
#import "DetectionSystemVersion.h"
#import "SBJson.h"
#import "MainSearchViewController.h"
#import "NSMutableArr.h"
#import "Common.h"

//#import <CoreTelephony/>
@interface SideMeunViewController (){
    int StatusH;
}

@end

@implementation SideMeunViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
     if(!self.title) self.title = @"百事搜";
    self.navigationController.navigationBarHidden=YES;
    if ([[DetectionSystemVersion alloc]Version]) {
        StatusH=20;
    }
    else{
        StatusH=0;
    }
//    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"SBFormattedPhoneNumber"]);
  
    [self SetTabelView];
    [self SetAllArr];
     [self ShowLocation];
    [self setupMenuBarButtonItems];
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(scrollTimer) userInfo:nil repeats:YES];
    [self getCurrentIP];
    [self GetDatas:@"上海"];
   
	// Do any additional setup after loading the view, typically from a nib.
}
-(void)userInfor{
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]){
        NSDictionary *dicUser=[[NSDictionary alloc]initWithObjectsAndKeys:@"",@"user",@"",@"name",@"男",@"sex",@"1990-1-1",@"born",nil];
        NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
        [user setObject:dicUser forKey:@"userInfor"];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"ForthLaunch"];
    }
}
-(void)SetTabelView{
    self.vieHead.frame=CGRectMake(self.vieHead.frame.origin.x, self.vieHead.frame.origin.y+StatusH, self.vieHead.frame.size.width, self.vieHead.frame.size.height);
    self.tabel.separatorStyle=UITableViewCellSeparatorStyleNone;
//    UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//    img.image=[UIImage imageNamed:@"bg"];
//    self.tabel.backgroundView=img;
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",APPID ];
    _iFlyRecognizerView = [[IFlyRecognizerView alloc] initWithOrigin:CGPointMake(20, 80) initParam:initString];
    _iFlyRecognizerView.delegate = self;

}

-(void)viewWillDisappear:(BOOL)animated{
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"daohanglan"] forBarMetrics:UIBarMetricsDefault];
    
    self.navigationController.navigationBarHidden=NO;
}
-(void)viewDidAppear:(BOOL)animated{
    [ btnCity setTitle:[Common GetCity] forState:UIControlStateNormal];
//    NSLog(@"%f %f",self.tabel.frame.origin.y ,self.tabel.frame.size.height);
}

#pragma mark 异步数据请求
-(void)GetDatas:(NSString *)location{
    tRequest=[[[ScreenAccess alloc]init]ASIHomerecommend];
    [tRequest setDelegate:self];
    [tRequest setUsername:@"allMessage"];
    [self GetWeather];
    
}
-(void)GetWeather{
    
    tRequest=[[[ScreenAccess alloc]init]ASIGetHomePageWeatherByCity];
    [tRequest setDelegate:self];
    [tRequest setUsername:@"weather"];
}
-(void)requestFinished:(ASIHTTPRequest*)request{
    
    NSString *response = [request responseString];
    SBJsonParser * parser = [[SBJsonParser alloc] init];
    NSMutableDictionary *Result = [parser objectWithString:response];
    
    if ([request.username isEqual:@"allMessage"]){
        BOOL IsSuccess=[[[Result objectForKey:@"Response"]objectForKey:@"status"]integerValue]==200?YES:NO;
            if (IsSuccess==YES) {
            if (arrReturn==nil) {
                arrReturn=[[NSMutableArray alloc]init];
            }
            NSArray *arr=[[Result objectForKey:@"Response"] objectForKey:@"recommend"];
                NSMutableArray *muArr=[[NSMutableArray alloc]init];
            for (int i=0; i<arr.count; i++) {
                if ([[[arr objectAtIndex:i]objectForKey:@"category"]integerValue]==0) {
                    [arrReturn addObject:[arr objectAtIndex:i]];
                }
                else{
                    [muArr addObject:[arr objectAtIndex:i]];
                }
               
            }
                [NSMutableArr sharedInstance].arrCuston=muArr;
                arr=Nil;
                muArr=Nil;
            [self.tabel reloadData];
         
                
        }
    }
        else if([request.username isEqual:@"weather"]){
           
                BOOL IsSuccess=[[[Result objectForKey:@"Response"]objectForKey:@"status"]integerValue]==200?YES:NO;
                if (IsSuccess==YES) {
                    NSString *city,*dayState,*lowest,*highest,*dayWindDirection,*nightWind;
                    if (weather==nil) {
                        city=[[[Result objectForKey:@"Response"] objectForKey:@"weather"] objectForKey:@"City"];
                        dayState=[[[Result objectForKey:@"Response"] objectForKey:@"weather"] objectForKey:@"DayState"];
                        lowest=[[[Result objectForKey:@"Response"] objectForKey:@"weather"] objectForKey:@"Lowest"];
                        highest=[[[Result objectForKey:@"Response"] objectForKey:@"weather"] objectForKey:@"Highest"];
                        dayWindDirection=[[[Result objectForKey:@"Response"] objectForKey:@"weather"] objectForKey:@"DayWindDirection"];
                        nightWind=[[[Result objectForKey:@"Response"] objectForKey:@"weather"] objectForKey:@"NightWind"];

                        
                    }
                    weather=[[NSString alloc] initWithFormat:@"%@天气：%@, %@~%@度, %@%@",city,dayState,lowest,highest,dayWindDirection,nightWind];
                    [self.tabel reloadData];
                    
        }
    }
    
    
}

-(void)requestFailed:(ASIHTTPRequest*)request{
    
}

//-(void)FlySynthesizer{
//    //语音播报
//    // 获得初始化参数，
//	NSString *initParam = [[NSString alloc] initWithFormat:@"server_url=%@,appid=%@",ENGINE_URL,APPID];
//    // 初始化语音合成控件
//	_iFlySynthesizerControl = [[IFlySynthesizerControl alloc] initWithOrigin:self.view.center initParam:initParam];
////    _iFlySynthesizerControl=[IFlySynthesizerControl cr]
//    _iFlySynthesizerControl.delegate = self;
//   	[self.navigationController.view addSubview:_iFlySynthesizerControl];
//    [_iFlySynthesizerControl setText:@"科大讯飞语音合成" params:nil];
//    [_iFlySynthesizerControl start];
//    [_iFlySynthesizerControl setShowUI:YES];
//    [_iFlySynthesizerControl setShowLog:YES];
//    [_iFlySynthesizerControl setBackgroundSound:@"1"];
//}
-(void)FlySynProduct{
   }
-(void)viewWillAppear:(BOOL)animated{
    self.txtSearch.text=@"";
    self.navigationController.navigationBarHidden=YES;

}

- (void)getCurrentIP
{
    NSURL *url = [NSURL URLWithString:@"http://automation.whatismyip.com/n09230945.asp"];
    __weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setCompletionBlock:^{
        
        NSString *responseString = [request responseString];
            NSLog(@"responseString = %@", responseString);
        if (responseString) {
            
            NSString *ip = [NSString stringWithFormat:@"%@", responseString];
            
            NSLog(@"responseString = %@", ip);
            
        }; 
        
        
        
    }];
    [request setFailedBlock:^{ 
        
    }]; 
    
}
-(void)SetAllArr{
    
    //    arrImg=[NSArray alloc]initWithObjects:<#(id), ...#>, nil];
    
    arrTitle=[[NSArray alloc]initWithObjects:@"常用号码",@"股票动态",@"美食菜谱",nil];
    
    arrDetailTitle=[[NSArray alloc]initWithObjects:@"美食",@"加油站",@"酒店",@"KTV",@"电影",@"银行",@"旅行社",@"医院",@"彩票",@"理财",@"法律",@"健康", nil];
    [self.tabel reloadData];
    
}
#pragma mark -
#pragma mark - UIBarButtonItems

- (void)setupMenuBarButtonItems {
    self.navigationItem.rightBarButtonItem = [self rightMenuBarButtonItem];
    if(self.menuContainerViewController.menuState == MFSideMenuStateClosed &&
       ![[self.navigationController.viewControllers objectAtIndex:0] isEqual:self]) {
        self.navigationItem.leftBarButtonItem = [self backBarButtonItem];
    }
//    else {
//        self.navigationItem.leftBarButtonItem = [self leftMenuBarButtonItem];
//    }
}
//
//- (UIBarButtonItem *)leftMenuBarButtonItem {
//    return [[UIBarButtonItem alloc]
//            initWithImage:[UIImage imageNamed:@"menu-icon.png"] style:UIBarButtonItemStyleBordered
//            target:self
//            action:@selector(leftSideMenuButtonPressed:)];
//}

- (UIBarButtonItem *)rightMenuBarButtonItem {
    return [[UIBarButtonItem alloc]
            initWithImage:[UIImage imageNamed:@"menu-icon.png"] style:UIBarButtonItemStyleBordered
            target:self
            action:@selector(rightSideMenuButtonPressed:)];
}
- (MFSideMenuContainerViewController *)menuContainerViewController {
    return (MFSideMenuContainerViewController *)self.navigationController.parentViewController;
}
- (UIBarButtonItem *)backBarButtonItem {
    return [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back-arrow"]
                                            style:UIBarButtonItemStyleBordered
                                           target:self
                                           action:@selector(backButtonPressed:)];
}


#pragma mark -
#pragma mark - UIBarButtonItem Callbacks

- (void)backButtonPressed:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)leftSideMenuButtonPressed:(id)sender {
    [self.menuContainerViewController toggleLeftSideMenuCompletion:^{
        [self setupMenuBarButtonItems];
    }];
}

- (void)rightSideMenuButtonPressed:(id)sender {
    [self.menuContainerViewController toggleRightSideMenuCompletion:^{
        [self setupMenuBarButtonItems];
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Return the number of rows in the section.
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.backgroundColor=[UIColor clearColor];
        
    }
    
    if (indexPath.section==0){
        [self Cell:cell.contentView];
    }
    else if (indexPath.section==1) {
        CGRect fram=CGRectMake(10, 0, 300, 30);
        UIView *vie=[self CustomCell:indexPath.section Fram:fram];
        UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(5, 0, vie.frame.size.width-5, vie.frame.size.height)];
        lab.text=weather;
        lab.font=[UIFont systemFontOfSize:13];
        lab.backgroundColor=[UIColor clearColor];
        [vie addSubview:lab];
        [cell.contentView addSubview:vie];
        lab.userInteractionEnabled=YES;
        lab.tag=310;
        UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                                 initWithTarget:self
                                                 action:@selector(GotoAdd:)];
        [tapRecognizer setDelegate:self];
        [lab addGestureRecognizer:tapRecognizer];
        [vie addSubview:lab];
        [cell.contentView addSubview:vie];

        
    }
    else if(indexPath.section==2){
        for (int i=0; i<3; i++) {
            CGRect fram=CGRectMake(10+102*i, 0, 96, 35);
            UIView *vie=[self CustomCell:indexPath.section Fram:fram];
            UIImageView *imgCell=[[UIImageView alloc]initWithFrame:CGRectMake(7, 9, 16, 16)];
            [imgCell setClipsToBounds:YES];
            [imgCell setContentMode:UIViewContentModeScaleAspectFit];
            imgCell.image=[UIImage imageNamed:[NSString stringWithFormat:@"CellSectionTwo%d",i]];
            [vie addSubview:imgCell];
            UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(30, 0, vie.frame.size.width-30, vie.frame.size.height)];
            lab.text=[arrTitle objectAtIndex:i];
            lab.backgroundColor=[UIColor clearColor];
             lab.font=[UIFont systemFontOfSize:13];
            lab.userInteractionEnabled=YES;
            lab.tag=210+i;
            UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                                     initWithTarget:self
                                                     action:@selector(GotoAdd:)];
            [tapRecognizer setDelegate:self];
            [lab addGestureRecognizer:tapRecognizer];
            [vie addSubview:lab];
            [cell.contentView addSubview:vie];

        }
        
    }
    else if(indexPath.section==3){
        CGRect fram=CGRectMake(10, 0, 300, 213);
        UIView *vie=[self CustomCell:indexPath.section Fram:fram];
        UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 50, 20)];
        lab.text=@"附件";
        lab.backgroundColor=[UIColor clearColor];
        lab.font=[UIFont systemFontOfSize:13];
        [vie addSubview:lab];
        for (int i=0; i<8; i++) {
            UIView *vieBtn=[[UIView alloc]initWithFrame:CGRectMake(25+(i%4)*69, 40+(i/4)*85, 46, 70)];
            vieBtn.backgroundColor=[UIColor clearColor];
            UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 46, 46)];
            [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"CellSectionThree%d",i]] forState:UIControlStateNormal];
            [vieBtn addSubview:btn];
            [btn addTarget:self action:@selector(PressSearch:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag=220+i;
            UILabel *labBtn=[[UILabel alloc]initWithFrame:CGRectMake(0, 50, 46, 20)];
            labBtn.text=[arrDetailTitle objectAtIndex:i];
            labBtn.backgroundColor=[UIColor clearColor];
            labBtn.textAlignment=NSTextAlignmentCenter;
            labBtn.font=[UIFont systemFontOfSize:13];
            [vieBtn addSubview:labBtn];
            [vie addSubview:vieBtn];
        }
        [cell.contentView addSubview:vie];
        
    }
    else if(indexPath.section==4){
        CGRect fram=CGRectMake(10, 0, 300, 118);
        UIView *vie=[self CustomCell:indexPath.section Fram:fram];
        UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 100, 20)];
        lab.text=@"本地生活";
        lab.backgroundColor=[UIColor clearColor];
        lab.font=[UIFont systemFontOfSize:13];
        [vie addSubview:lab];
        for (int i=0; i<4; i++) {
            UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(12+(i%4)*70, 40+(i/4)*85, 65, 62)];
            [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"CellSectionFour%d",i]] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(PressSearch:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag=228+i;
            [vie addSubview:btn];
        }
        [cell.contentView addSubview:vie];
    }
   
    return cell;
}
-(UIView *)CustomCell:(int)row Fram:(CGRect)fram{
    UIView *vie=[[UIView alloc]initWithFrame:fram];
    vie.backgroundColor=[UIColor clearColor];
    UIImageView *img=[[UIImageView alloc]init];
    img.image=[UIImage imageNamed:[NSString stringWithFormat:@"imgCell%d",row]];
    img.frame=CGRectMake(0, 0, vie.frame.size.width, vie.frame.size.height);
    [vie addSubview:img];
    return vie;
}
-(void)Cell:(UIView *)cell{
    CGRect fram=CGRectMake(10, 0, 300, 46);
    scrContest=[[UIScrollView alloc]initWithFrame:fram];
    scrContest.backgroundColor=[UIColor clearColor];
    scrContest.showsHorizontalScrollIndicator=NO;
    scrContest.showsVerticalScrollIndicator=NO;
    scrContest.scrollEnabled=NO;
    int addCounts=arrReturn.count;
 scrContest.contentSize=CGSizeMake(scrContest.frame.size.width*addCounts, scrContest.frame.size.height);
    for (int i=0; i<addCounts; i++) {
        UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(300*i, 0, 300, 30)];
        lab.text=[NSString stringWithFormat:@"%@",[[arrReturn objectAtIndex:i] objectForKey:@"text"] ];
        lab.font=[UIFont systemFontOfSize:13];
        lab.backgroundColor=[UIColor clearColor];
        lab.textColor=[UIColor grayColor];
        lab.textAlignment=NSTextAlignmentCenter;
        lab.tag=200+i;
        lab.userInteractionEnabled=YES;
        UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                                 initWithTarget:self
                                                 action:@selector(GotoUrl:)];
        [tapRecognizer setDelegate:self];
        [lab addGestureRecognizer:tapRecognizer];
        [scrContest addSubview:lab];
    }
    pageCell =[[UIPageControl alloc]initWithFrame:CGRectMake(10, 30, 300, 2)];
    pageCell.numberOfPages=addCounts;
    pageCell.currentPageIndicatorTintColor=[UIColor orangeColor];
    pageCell.pageIndicatorTintColor=[UIColor lightGrayColor];
    [cell addSubview:pageCell];
    UIImageView *imgCell=[[UIImageView alloc]initWithFrame:CGRectMake(35, 40, 250, 3)];
    imgCell.image=[UIImage imageNamed:@"imgCell0"];
    [cell addSubview:imgCell];
    [cell addSubview:scrContest];

}
- (void)GotoAdd:(UITapGestureRecognizer *)sender {
    UILabel *lab=(UILabel *)sender.view;
    
    MainSearchViewController *mainSearch=[[MainSearchViewController alloc]init];
    if (sender.view.tag==310) {
        mainSearch.strSearch=@"今日天气";

    }
    else{
    if ([lab.text isEqual:@"常用号码"]) {
        mainSearch.isUrl=1;
        mainSearch.strSearch=@"http://116.228.55.29/LBSInterface/callNumbers.html?c=1";
        
    }
    else if([lab.text isEqual:@"美食菜谱"]){
        mainSearch.strSearch=@"菜谱";

    }
    else{
        mainSearch.strSearch=lab.text;
    }
    }
    [self.navigationController pushViewController:mainSearch animated:YES];
    
}

- (void)GotoUrl:(UITapGestureRecognizer *)sender {
     MainSearchViewController *mainSearch=[[MainSearchViewController alloc]init];
    if ([[[arrReturn objectAtIndex:sender.view.tag-200] objectForKey:@"mode"] integerValue] ==0 ) {
        mainSearch.strSearch=[[arrReturn objectAtIndex:sender.view.tag-200] objectForKey:@"query"];
        
    }
    else{
        mainSearch.strSearch=[[arrReturn objectAtIndex:sender.view.tag-200] objectForKey:@"hyperlinkurl"];
        if ([[[arrReturn objectAtIndex:sender.view.tag-200] objectForKey:@"query"]  isEqual:@""]) {
           mainSearch.isUrl=2;
        }
        else{
             mainSearch.isUrl=3;
        }
    }
    [self.navigationController pushViewController:mainSearch animated:YES];
    
}
-(void)PressSearch:(UIButton *)button{
    
    MainSearchViewController *mainSearch=[[MainSearchViewController alloc]init];
    if ([[arrDetailTitle objectAtIndex:button.tag-220] isEqual:@"美食"]) {
        mainSearch.strSearch=@"饭店";
    }
    else if([[arrDetailTitle objectAtIndex:button.tag-220] isEqual:@"电影"]){
        mainSearch.strSearch=@"电影院";
    }
    else{
    mainSearch.strSearch=[arrDetailTitle objectAtIndex:button.tag-220];
    }
    [self.navigationController pushViewController:mainSearch animated:YES];
}
-(void)scrollTimer{
    CGFloat currentOffset = scrContest.contentOffset.x;
    if (currentOffset<scrContest.contentSize.width-scrContest.frame.size.width) {
        CGFloat newOffset = currentOffset + scrContest.frame.size.width;
        [UIScrollView beginAnimations:nil context:NULL];
        [UIScrollView setAnimationDuration:2.1];
        [scrContest setContentOffset:CGPointMake(newOffset,2.0) animated:YES];
        [UIScrollView commitAnimations];
        pageCell.currentPage=currentOffset/scrContest.frame.size.width+1;
        
    }
    else{
        [UIScrollView beginAnimations:nil context:NULL];
        [UIScrollView setAnimationDuration:2.1];
        [scrContest setContentOffset:CGPointMake(2,2.0) animated:YES];
        [UIScrollView commitAnimations];
        pageCell.currentPage=0;
    }
    
}

#pragma mark Table Delegate Methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    int rowH;
    if (indexPath.section==0) {
        rowH=46;
        
    }
    else if (indexPath.section==1) {
        rowH=30;
        
    }
    else if(indexPath.section==2){
        rowH=35;

    }
    else if(indexPath.section==3){
        rowH=213;

    }
    else {
        rowH=118;

    }
//    else if(indexPath.section==4){
//        
//    }
    return rowH;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *result = nil;
    result = [[UIView alloc] initWithFrame:CGRectZero];
    result.backgroundColor=[UIColor clearColor];
    return result;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 10;
    }
   else if (section==2) {
        return 7;
    }
   else if (section==4) {
       return 10;
   }
    return 10;
}
// custom view for header. will be adjusted to default or specified header height{
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==4) {
        return 10;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *result = nil;
    result = [[UIView alloc] initWithFrame:CGRectZero];
    result.backgroundColor=[UIColor clearColor];
    return result;
}

//定位
-(void)ShowLocation{
    if ([CLLocationManager locationServicesEnabled]){
        self.myLocationManager = [[CLLocationManager alloc] init];
        self.myLocationManager.distanceFilter=1000.0f;
        self.myLocationManager.desiredAccuracy=kCLLocationAccuracyBest;
        self.myLocationManager.delegate = self;
        //        self.myLocationManager.purpose =
        //        @"定位用户当前位置";
        
        [self.myLocationManager startUpdatingLocation];
        
    } else {
        UIAlertView *alr=[[UIAlertView alloc]initWithTitle:@"无法获取你当前位置信息" message:@"请到手机系统[设置]->[隐私]->[定位服务]中打开定位服务，并允许百事搜使用定位服务" delegate:Nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alr show];
    }
    
    
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation{
    NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:@"%f",newLocation.coordinate.longitude],@"gpsx",[NSString stringWithFormat:@"%f",newLocation.coordinate.latitude],@"gpsy",nil];
    NSUserDefaults *use=[NSUserDefaults standardUserDefaults];
    [use setObject:dic forKey:@"Location"];

//    NSLog(@"经纬度：%@",dic);
    /* We received the new location */
    
//    CLLocation *NextLoc=[[CLLocation alloc]initWithLatitude:28.6833333333333 longitude:115.9];
// CLLocation *NextLoc=[[CLLocation alloc]initWithLatitude:39.974228f longitude:116.467430f];
    
//    NSLog(@"Latitude = %f", newLocation.coordinate.latitude);
//    
//    NSLog(@"Longitude = %f", newLocation.coordinate.longitude);
//    CLLocation *location = [[CLLocation alloc]
//                            initWithLatitude:newLocation.coordinate.latitude
//                            longitude:newLocation.coordinate.longitude];
//    
    self.myGeocoder = [[CLGeocoder alloc] init];
    [self.myGeocoder reverseGeocodeLocation:newLocation
                          completionHandler:^(NSArray *placemarks, NSError *error) {
                              if (error == nil &&[placemarks count] > 0){
                                  CLPlacemark *placemark = placemarks[0];
//                                  NSLog(@"%@",placemark);
                                  /* We received the results */
//                                    NSString *addressString = CFBridgingRelease(CFBridgingRetain(ABCreateStringWithAddressDictionary(placemark.name, NO)));
//                                  NSDictionary *dic=placemark.addressDictionary;
//                                  NSLog(@"当前字典%@",placemark.addressDictionary);
//                                  NSLog(@"当前字典   %@",[dic objectForKey:@"Country"]);
//                                   NSLog(@"当前字典   %@",[dic objectForKey:@"CountryCode"]);
//                                  NSLog(@"当前字典   %@",[[dic objectForKey:@"FormattedAddressLines"] objectAtIndex:0]);
//                                   NSLog(@"当前字典   %@",[dic objectForKey:@"Name"]);
//                                   NSLog(@"当前字典   %@",[dic objectForKey:@"State"]);
//                                   NSLog(@"当前字典  %@",[dic objectForKey:@"Street"]);
//                                  NSLog(@"当前字典  %@",[dic objectForKey:@"SubLocality"]);
//                                   NSLog(@"当前字典  %@",[dic objectForKey:@"SubThoroughfare"]);
//                                  NSLog(@"当前字典  %@",[dic objectForKey:@"Thoroughfare"]);
//                                  NSLog(@"name  %@",placemark.name);
//                                  NSLog(@"locality  %@",placemark.locality);
                                  if ([placemark.locality isEqual:[NSNull null]]) {
                                      [self WriteCity:placemark.administrativeArea Province:@""];
                                  }
                                  else{
                                       [self WriteCity:placemark.locality Province:placemark.administrativeArea];
                                  }
//                                   NSLog(@"subLocality  %@",placemark.locality);
//                                   NSLog(@"administrativeArea  %@",placemark.administrativeArea);
//                                   NSLog(@"subAdministrativeArea  %@",placemark.subAdministrativeArea);
//                                   NSLog(@"postalCode  %@",placemark.postalCode);
//                                   NSLog(@"ISOcountryCode  %@",placemark.ISOcountryCode);
//                                   NSLog(@"country  %@",placemark.country);
//                                  NSLog(@"inlandWater  %@",placemark.inlandWater);
//
//                                  NSLog(@"ocean  %@",placemark.ocean);
//
//                                  NSLog(@"areasOfInterest  %@",placemark.areasOfInterest);

//                                  NSLog(@"Country = %@", placemark.country);
//                                  NSLog(@"Postal Code = %@", placemark.thoroughfare);
//                                  NSLog(@"Locality = %@", placemark.locality);
                                  
                              }
                              
                              else if (error == nil &&[placemarks count] == 0){
//                                  NSLog(@"No results were returned.");
                              }
                              else if (error != nil){
//                                  NSLog(@"An error occurred = %@", error);
                              }
                              
                          }];
    
     [self.myLocationManager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error{ /* Failed to receive user's location */
    UIAlertView *alr=[[UIAlertView alloc]initWithTitle:Nil message:@"关闭飞行模式或者使用无线局域网来访问数据" delegate:Nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alr show];
}
//保存城市地址
-(void)WriteCity:(NSString *)strSelect Province:(NSString *)province{
//    NSLog(@"%@  %@",strSelect,province);
    NSRange range;
    if ([strSelect hasSuffix:@"市"]) {
        range = [strSelect rangeOfString:@"市"];
    }
    else if([strSelect hasSuffix:@"自治区"]){
        range = [strSelect rangeOfString:@"自治区"];
        
    }
    else if([strSelect hasSuffix:@"自治县"]){
        range = [strSelect rangeOfString:@"自治县"];
        
    }
    else if([strSelect hasSuffix:@"自治州"]){
        range = [strSelect rangeOfString:@"自治州"];
        
    }
    else if([strSelect hasSuffix:@"地区"]){
        range = [strSelect rangeOfString:@"地区"];
        
    }
    else if([strSelect hasSuffix:@"特别行政区"]){
        range = [strSelect rangeOfString:@"特别行政区"];
        
    }
   
    strSelect=[strSelect substringToIndex:range.location];
    [Common SetCity:strSelect];
    strSelect=province;
    if ([province hasSuffix:@"省"]) {
        range = [province rangeOfString:@"省"];
        strSelect=[province substringToIndex:range.location];
    }
    [Common SetProvince:strSelect];
    [ btnCity setTitle:[Common GetCity] forState:UIControlStateNormal];

 
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
     [textField resignFirstResponder];
    if (![textField.text isEqual:@""]) {
        MainSearchViewController *mainSearch=[[MainSearchViewController alloc]init];
        mainSearch.strSearch=textField.text;
        [self.navigationController pushViewController:mainSearch animated:YES];
    }
    return YES;
}

- (IBAction)PressCity:(UIButton *)sender {
     [self.txtSearch resignFirstResponder];
    ChangCity *chanCity=[[ChangCity alloc]init];
    chanCity.strCurrentCiy=sender.currentTitle;
    [self.navigationController pushViewController:chanCity animated:YES];
//    ChangCity *chan=[[ChangCity alloc]init];
//    [self.navigationController pushViewController:chan animated:YES];

}

- (IBAction)PressIFly:(id)sender {
    [self.txtSearch resignFirstResponder];
//    语音合成
//    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",APPID ];
//    
//    _iFlySynthesizerView = [[IFlySynthesizerView alloc] initWithOrigin:CGPointMake(20, 80) params:initString];
//       _iFlySynthesizerView.delegate = self;
//   
//    //    [_iFlySynthesizerView setParameter:@"params" value:@"bgs=1"];
//    [_iFlySynthesizerView startSpeaking:ASRWORD];

    
//    语音识别
    
    [_iFlyRecognizerView setParameter:@"grammarID" value:_grammarID];
    
    // 参数设置
    [_iFlyRecognizerView setParameter:@"domain" value:@"iat"];
//    [_iFlyRecognizerView setParameter:@"vad_bos" value:@"500"];
    [_iFlyRecognizerView setParameter:@"sample_rate" value:@"16000"];
    [_iFlyRecognizerView setParameter:@"vad_eos" value:@"1800"];
    [_iFlyRecognizerView setParameter:@"vad_bos" value:@"6000"];
    [_iFlyRecognizerView setParameter:@"asr_ptt" value:@"0"];
    [_iFlyRecognizerView start];

}
#pragma mark -
#pragma mark IFlySynthesizerControlDelegate methods
- (void)onResult:(IFlyRecognizerView *)iFlyRecognizerView theResult:(NSArray *)resultArray{
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
     self.txtSearch.text = [NSString stringWithFormat:@"%@",result];
    if (![result isEqual:@""]) {
         [_iFlyRecognizerView removeFromSuperview];
        MainSearchViewController *mainSearch=[[MainSearchViewController alloc]init];
        mainSearch.strSearch=result;
        [self.navigationController pushViewController:mainSearch animated:YES];
       
    }
//    NSLog(@"成功了吗%@",resultArray);
}
- (void)onEnd:(IFlyRecognizerView *)iFlyRecognizerView theError:(IFlySpeechError *) error{
//    NSLog(@"错误了嘛%@",error);
}
@end
